using System.Diagnostics;
using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;

partial struct BulletControlSystem : ISystem
{
    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        
    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        var gamePre=SystemAPI.GetSingleton<GamePreComponent>();
        EntityCommandBuffer ecb=new EntityCommandBuffer(Allocator.Temp);
        foreach(var(trans,bulletData,bulletEn) in SystemAPI.Query<RefRO<LocalTransform>,RefRW<BulletDataComponet>>().WithEntityAccess() ){
            bulletData.ValueRW.lifeTimer-=SystemAPI.Time.DeltaTime;
            if(bulletData.ValueRO.lifeTimer<=0){
                ecb.DestroyEntity(bulletEn);
            }else{
            if(bulletData.ValueRO.isPlayer){
                foreach(var (enemyTrans,atri,enemyEn) in SystemAPI.Query<RefRO<LocalTransform>,RefRW<CharacterAttributeComponent>>().WithAny<EnemyComponent>()
                .WithEntityAccess()){
                    if(math.distance(trans.ValueRO.Position,enemyTrans.ValueRO.Position)<=0.2f){
                        atri.ValueRW.hp-=bulletData.ValueRO.demage;
                        if(atri.ValueRO.hp<=0){
                            var expDrop= ecb.Instantiate(gamePre.expPre);
                            var expTrans= SystemAPI.GetComponent<LocalTransform>(gamePre.expPre);
                            expTrans.Position=enemyTrans.ValueRO.Position;
                            ecb.SetComponent(expDrop,expTrans);
                            ecb.DestroyEntity(enemyEn);                           
                        }
                        ecb.DestroyEntity(bulletEn);
                    }
                }
            }
            }

        }
        ecb.Playback(state.EntityManager);
        ecb.Dispose();
    }

    [BurstCompile]
    public void OnDestroy(ref SystemState state)
    {
        
    }
}
